package com.itheima.ydd.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.ydd.common.BusinessException;
import com.itheima.ydd.common.UserHolder;
import com.itheima.ydd.dto.RoleDto;
import com.itheima.ydd.entity.SysMenu;
import com.itheima.ydd.entity.SysRole;
import com.itheima.ydd.entity.SysRoleMenu;
import com.itheima.ydd.entity.SysUser;
import com.itheima.ydd.mapper.SysRoleMapper;
import com.itheima.ydd.service.ISysMenuService;
import com.itheima.ydd.service.ISysRoleMenuService;
import com.itheima.ydd.service.ISysRoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.ydd.service.ISysUserService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 角色表 服务实现类
 * </p>
 */
@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper,SysRole> implements ISysRoleService {
    @Autowired
    private SysRoleMapper roleMapper;

    @Autowired
    private ISysMenuService menuService;

    @Autowired
    private ISysRoleMenuService roleMenuService;

    @Autowired
    private ISysUserService userService;

    //判断权限的方法
    @Override
    public  Boolean RoleUtils(String oneRole, String twoRole, String thirdRole) {
        LambdaQueryWrapper<SysRole> roleLambdaQueryWrapper = new LambdaQueryWrapper<>();
        //获取登录人员信息，把test类型转化为string，去掉[]和""
        String userId = UserHolder.getUserId();
        SysUser user2 = userService.getById(userId);
        String strip = StringUtils.strip(user2.getRoleId(), "[]");
        String[] split = strip.split(",");
        for (int i = 0; i < split.length; i++) {
            split[i]=StringUtils.replace(split[i], "\"", "");
        }
        //String replace = StringUtils.replace(strip, "\"", "");
        //String[] split = replace.split(",");
        //注入条件
        roleLambdaQueryWrapper.in(SysRole::getId,split);
        List<SysRole> list1 = roleMapper.selectList(roleLambdaQueryWrapper);
        //获取id
        List<String> collect = list1.stream().map((item) -> {
            return item.getId();
        }).collect(Collectors.toList());
        //根据权限id去查询是否有用户管理权限
        LambdaQueryWrapper<SysRoleMenu> roleMenuLambdaQueryWrapper=new LambdaQueryWrapper<>();
        roleMenuLambdaQueryWrapper.in(SysRoleMenu::getRoleId,collect);
        List<SysRoleMenu> list = roleMenuService.list(roleMenuLambdaQueryWrapper);
        for (SysRoleMenu roleMenu : list) {
            String menuId = roleMenu.getMenuId();
            SysMenu menu = menuService.getById(menuId);
            //一级权限
            if (oneRole.equals(menu.getTitle())) {
                List<SysRoleMenu> list3 = roleMenuService.list(roleMenuLambdaQueryWrapper);
                for (SysRoleMenu roleMenu1 : list3) {
                    String menuId1 = roleMenu1.getMenuId();
                    SysMenu menu1 = menuService.getById(menuId1);
                    //二级权限
                    if (twoRole.equals(menu1.getTitle())) {
                        List<SysRoleMenu> list4 = roleMenuService.list(roleMenuLambdaQueryWrapper);
                        for (SysRoleMenu roleMenu2 : list4) {
                            String menuId2 = roleMenu2.getMenuId();
                            SysMenu menu2 = menuService.getById(menuId2);
                            //三级权限
                            if (thirdRole.equals(menu2.getTitle())) {
                                return true;
                            }
                        }
                    }
                }
            }
        }
        return false;
    }

    @Override
    public List<String> roleNameList(String role_id) {
        String[] strings = role_id.split(",");
        LambdaQueryWrapper<SysRole> roleLambdaQueryWrapper = new LambdaQueryWrapper<>();
        roleLambdaQueryWrapper.in(SysRole::getId, strings);
        List<SysRole> roles = this.list(roleLambdaQueryWrapper);
        List<String> roleNameList = CollUtil.getFieldValues(roles, "name", String.class);
        return roleNameList;
    }

    @Override
    public List<RoleDto> getByMenu() {
        List<SysRole> roleList = this.list();
        List<RoleDto> roleDtoList = roleList.stream().map(role -> {
            RoleDto roleDto = new RoleDto();
            String id = role.getId();
            List<String> menu = roleMapper.getMenu(id);
            String role_menus = "";
            for (int i = 0; i < menu.size(); i++) {
                if(i < menu.size()-1){
                    role_menus += menu.get(i)+",";
                }else {
                    role_menus += menu.get(i);
                }

            }
            roleDto.setRole_menus(role_menus);
            BeanUtils.copyProperties(role, roleDto);
            return roleDto;
        }).collect(Collectors.toList());

        return roleDtoList;
    }

    @Override
    public RoleDto getRole(String id) {
        RoleDto roleDto=new RoleDto();
        SysRole sysRole = this.getById(id);
        BeanUtils.copyProperties(sysRole,roleDto);
        List<String> list = roleMapper.getMenu(sysRole.getId());
        List<SysMenu> menuList = menuService.listByIds(list);
        List<SysMenu> menus = menuService.getMenuMethod(menuList);
        roleDto.setAuthList(menus);
        return roleDto;
    }

    @Override
    public void updateMenu(List<String> menuids, String id) {
        LambdaQueryWrapper<SysRoleMenu> lqw=new LambdaQueryWrapper<>();
        lqw.eq(SysRoleMenu::getRoleId,id);
        roleMenuService.remove(lqw);

        List<SysRoleMenu> roleMenus=new ArrayList<>();
        for (String menuid : menuids) {
            SysRoleMenu roleMenu=new SysRoleMenu();
            roleMenu.setRoleId(id);
            roleMenu.setMenuId(menuid);
            roleMenus.add(roleMenu);
        }
        roleMenuService.saveBatch(roleMenus);

    }

    @Override
    public void saveWithMenu(RoleDto roleDto) {
        LambdaQueryWrapper<SysRole> lqw=new LambdaQueryWrapper<>();
        lqw.eq(SysRole::getName,roleDto.getName());
        List<SysRole> list = this.list(lqw);
        if (list.size()>0){
            throw new BusinessException("该角色名称已存在,请重新添加");
        }
        this.save(roleDto);

        List<String> menuids = roleDto.getMenuids();
        String id = roleDto.getId();

        List<SysRoleMenu> roleMenus=new ArrayList<>();
        for (String menuid : menuids) {
            SysRoleMenu roleMenu=new SysRoleMenu();
            roleMenu.setRoleId(id);
            roleMenu.setMenuId(menuid);
            roleMenus.add(roleMenu);
        }
        roleMenuService.saveBatch(roleMenus);
    }

    @Override
    public void del(String id) {
        Boolean flag=false;
        List<SysUser> userList = userService.list();
        for (SysUser user : userList) {
            String roleId = user.getRoleId();
            if (roleId.contains(id)){
                flag=true;
                break;
            }
        }
        if (flag){
            throw new BusinessException("该角色下绑定了用户,请先删除用户后再操作");
        }
        this.removeById(id);
    }
}
